/*
 * @Author: intellectual-seeker 3336339701@qq.com
 * @Date: 2025-11-18 12:55:37
 * @LastEditors: intellectual-seeker 3336339701@qq.com
 * @LastEditTime: 2025-11-18 15:33:09
 * @FilePath: /code/lesson34/test1/UdpClient.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <string>
#include <cstring>
#include "Log.hpp"
#include <arpa/inet.h>
#include "InetAddr.hpp"

void Usage(std::string proc)
{
    std::cout << "Usage:\n\t" << proc << " server_ip server_port\n" << std::endl;
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    //1. 创建socket fd
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        LOG(FATAL, "socket create error %s %d", strerror(errno), errno);
    }
    LOG(INFO, "socket create success");

    //转网络字节序
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    uint16_t port = std::stoi(argv[2]);
    server.sin_port = htons(port);
    server.sin_addr.s_addr = inet_addr(argv[1]);

    while(true)
    {
        std::string message;
        std::cout << "send message# ";
        getline(std::cin, message);
        sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr*)&server, sizeof(server));

        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        char buf[1024] = { 0 };
        recvfrom(sockfd, buf, sizeof(buf) - 1, 0, (struct sockaddr*)&peer, &len);
        InetAddr addr(peer);
        LOG(INFO, "get message from [%s:%d] %s", addr.Ip().c_str(), addr.Port(), buf);
    }

    return 0;
}